package com.jingdianjichi.subject.application.context;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LoginContextHolder {

    /*public static ThreadLocal<Map<String,Object>> THREAD_LOCAL =new ThreadLocal<>();*/
    public static InheritableThreadLocal<Map<String,Object>> THREAD_LOCAL =new InheritableThreadLocal<>();

    public static void set(String key,String val){
        Map<String,Object> map = getThreadLocalMap();
        map.put(key,val);
    }

    public static Object get(String key){
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    public static void remove(){
        THREAD_LOCAL.remove();
    }


    //将map放到threadlocal里面
    public static Map<String,Object> getThreadLocalMap(){
        //从threadlocal中取出map 如果为空 那么就新建一个
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }
}
